"use client"

import { useState } from "react"
import { View, Text, StyleSheet, TouchableOpacity, ScrollView, Platform, Alert } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import { ArrowLeft, Plus, BookOpen, Star } from "lucide-react-native"
import { useRouter } from "expo-router"
import { theme } from "@/constants/theme"
import { FavoriteCollection } from "@/components/favorites/FavoriteCollection"
import { AddCollectionModal } from "@/components/favorites/AddCollectionModal"

// 模拟收藏本数据
const FAVORITE_COLLECTIONS = [
    {
        id: "default",
        title: "单词本",
        tag: "默认",
        count: 0,
        color: "#8A70D6",
        isDefault: true,
    },
    {
        id: "yuoiu",
        title: "yuoiu",
        count: 1,
        color: "#8A70D6",
    },
    {
        id: "english",
        title: "英语词汇",
        count: 12,
        color: "#5B8EF4",
    },
    {
        id: "science",
        title: "科学术语",
        count: 8,
        color: "#34C759",
    },
    {
        id: "custom1",
        title: "考试词汇",
        tag: "重要",
        count: 25,
        color: "#FF9500",
    },
    {
        id: "custom2",
        title: "日常用语",
        count: 15,
        color: "#8A70D6",
    },
    {
        id: "custom3",
        title: "旅游词汇",
        count: 18,
        color: "#5B8EF4",
    },
    {
        id: "custom4",
        title: "商务英语",
        count: 22,
        color: "#34C759",
    },
    {
        id: "custom5",
        title: "医学术语",
        count: 14,
        color: "#FF9500",
    },
]

export default function FavoritesScreen() {
    const router = useRouter()
    const [collections, setCollections] = useState(FAVORITE_COLLECTIONS)
    const [modalVisible, setModalVisible] = useState(false)
    const [editModalVisible, setEditModalVisible] = useState(false)
    const [selectedCollection, setSelectedCollection] = useState(null)

    const handleBack = () => {
        router.back()
    }

    const handleCreateCollection = () => {
        setModalVisible(true)
    }

    const handleAddCollection = (name: string) => {
        // 创建新收藏本
        const newCollection = {
            id: `new-${Date.now()}`,
            title: name,
            count: 0,
            color: getRandomColor(),
        }
        setCollections([...collections, newCollection])
        setModalVisible(false)

        // 显示成功提示
        Alert.alert("创建成功", `收藏本"${name}"已创建`)
    }

    const handleCollectionPress = (collectionId: string) => {
        // 找到对应的收藏本
        const collection = collections.find((c) => c.id === collectionId)
        if (collection) {
            // 跳转到学习页面
            router.push({
                pathname: "/learning-screen",
                params: {
                    source: "book",
                    id: collection.id,
                    title: collection.title,
                    count: collection.count,
                },
            })
        }
    }

    // 添加处理编辑的函数
    const handleEditCollection = (collection) => {
        setSelectedCollection(collection)
        setEditModalVisible(true)
    }

    // 添加更新收藏本的函数
    const handleUpdateCollection = (id, newName) => {
        setCollections(
            collections.map((collection) => (collection.id === id ? { ...collection, title: newName } : collection)),
        )

        // 显示成功提示
        Alert.alert("更新成功", `收藏本名称已更新为"${newName}"`)
    }

    // 添加删除收藏本的函数
    const handleDeleteCollection = (id) => {
        setCollections(collections.filter((collection) => collection.id !== id))

        // 显示成功提示
        Alert.alert("删除成功", "收藏本已删除")
    }

    // 生成随机颜色
    const getRandomColor = () => {
        const colors = ["#8A70D6", "#5B8EF4", "#34C759", "#FF9500", "#FF3B30"]
        return colors[Math.floor(Math.random() * colors.length)]
    }

    return (
        <SafeAreaView style={styles.container} edges={["top"]}>
            <LinearGradient
                colors={theme.colors.neutral.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.gradientBackground}
            >
                {/* 头部 */}
                <View style={styles.header}>
                    <TouchableOpacity onPress={handleBack} style={styles.backButton}>
                        <ArrowLeft size={24} color={theme.colors.neutral.black} />
                    </TouchableOpacity>
                    <Text style={styles.headerTitle}>收藏本</Text>
                    <View style={{ width: 40 }} />
                </View>

                {/* 内容区域 */}
                <ScrollView style={styles.content} contentContainerStyle={styles.contentContainer}>
                    {/* 收藏本统计 */}
                    <View style={styles.statsContainer}>
                        <View style={styles.statCard}>
                            <View style={styles.statIconContainer}>
                                <BookOpen size={20} color={theme.colors.primary.default} />
                            </View>
                            <Text style={styles.statValue}>{collections.length}</Text>
                            <Text style={styles.statLabel}>收藏本</Text>
                        </View>

                        <View style={styles.statCard}>
                            <View style={styles.statIconContainer}>
                                <Star size={20} color={theme.colors.secondary.orange.default} />
                            </View>
                            <Text style={styles.statValue}>
                                {collections.reduce((total, collection) => total + collection.count, 0)}
                            </Text>
                            <Text style={styles.statLabel}>收藏单词</Text>
                        </View>
                    </View>

                    {/* 收藏本列表 */}
                    <Text style={styles.sectionTitle}>我的收藏本</Text>
                    <View style={styles.collectionsGrid}>
                        {collections.map((collection) => (
                            <FavoriteCollection
                                key={collection.id}
                                collection={collection}
                                onPress={() => handleCollectionPress(collection.id)}
                                onEdit={handleEditCollection}
                            />
                        ))}
                    </View>
                </ScrollView>

                {/* 创建新收藏本按钮 */}
                <TouchableOpacity style={styles.fabButton} onPress={handleCreateCollection}>
                    <LinearGradient
                        colors={theme.colors.primary.gradient}
                        start={{ x: 0, y: 0 }}
                        end={{ x: 1, y: 1 }}
                        style={styles.fabGradient}
                    >
                        <Plus size={24} color={theme.colors.neutral.white} />
                    </LinearGradient>
                </TouchableOpacity>

                {/* 添加收藏本模态框 */}
                <AddCollectionModal
                    visible={modalVisible}
                    onClose={() => setModalVisible(false)}
                    onConfirm={handleAddCollection}
                />
            </LinearGradient>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
        borderBottomWidth: 1,
        borderBottomColor: "rgba(0, 0, 0, 0.05)",
    },
    backButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    headerTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
    },
    content: {
        flex: 1,
    },
    contentContainer: {
        padding: theme.spacing.lg,
        paddingBottom: 100, // 为底部按钮留出空间
    },
    statsContainer: {
        flexDirection: "row",
        marginBottom: theme.spacing.xl,
        gap: theme.spacing.md,
    },
    statCard: {
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        alignItems: "center",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.5,
                shadowRadius: 4,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    statIconContainer: {
        width: 40,
        height: 40,
        borderRadius: 20,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
        marginBottom: theme.spacing.sm,
    },
    statValue: {
        fontSize: theme.fontSize.xl,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.xs,
    },
    statLabel: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
    },
    sectionTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.lg,
    },
    collectionsGrid: {
        flexDirection: "row",
        flexWrap: "wrap",
        justifyContent: "flex-start", // Changed to flex-start
        gap: theme.spacing.md,
    },
    fabButton: {
        position: "absolute",
        bottom: Platform.OS === "ios" ? 40 : 24,
        right: 24,
        width: 56,
        height: 56,
        borderRadius: 28,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 8,
            },
        }),
    },
    fabGradient: {
        width: "100%",
        height: "100%",
        borderRadius: 28,
        alignItems: "center",
        justifyContent: "center",
    },
})

